package com.yuanian.ecsplus.handler;

import com.yuanian.dp.common.vo.CustomeFieldValueVo;
import com.yuanian.ecsplus.annotation.Attachment;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class ResultHandlerFactory {

    private static final Map<Class<?>, ResultHandler> handlerMap = new HashMap<>();

    static {
        addHandler(Attachment.class, new AttachmentResultHandler());
        addHandler(BigDecimal.class, new BigDecimalResultHandler());
        addHandler(CustomeFieldValueVo.class, new CustomerFieldValueVoHandler());
        addHandler(Other.class, new CommonResultHandler());
    }

    /**
     * 获取结果处理器
     * @param field
     * @return
     */
    public static ResultHandler getHandler(Field field) {
        //获取字段上的注解
        Annotation[] annotations = field.getDeclaredAnnotations();
        //字段上没注解
        if (annotations == null || annotations.length == 0) {
            return handlerMap.get(field.getType()) == null ? handlerMap.get(Other.class) : handlerMap.get(field.getType());
        } else {
            ResultHandler handler = null;
            for (Annotation annotation : annotations) {
                handler = handlerMap.get(annotation.annotationType());
                //字段注解没有处理器
                if (handler == null) {
                    continue;
                }
            }
            return handler == null ? handlerMap.get(Other.class) : handler;
        }
    }

    public static ResultHandler getHandler(Class clz) {
       return handlerMap.getOrDefault(clz, handlerMap.get(Other.class));
    }

    public static void addHandler(Class clz, ResultHandler resultHandler) {
        handlerMap.putIfAbsent(clz, resultHandler);
    }

    class Other {

    }

}
